package com.hyl.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hyl.common.exception.NoStockException;
import com.hyl.common.to.mq.OrderTo;
import com.hyl.common.to.mq.SeckillOrderTo;
import com.hyl.common.utils.R;
import com.hyl.common.vo.MemberRespVo;
import com.hyl.gulimall.order.constant.OrderConstant;
import com.hyl.gulimall.order.entity.OrderItemEntity;
import com.hyl.gulimall.order.entity.PaymentInfoEntity;
import com.hyl.gulimall.order.enume.OrderStatusEnum;
import com.hyl.gulimall.order.feign.CartFeignService;
import com.hyl.gulimall.order.feign.MemberFeignService;
import com.hyl.gulimall.order.feign.ProductFeignService;
import com.hyl.gulimall.order.feign.WareFeignService;
import com.hyl.gulimall.order.interceptor.LoginUserInterceptor;
import com.hyl.gulimall.order.service.OrderItemService;
import com.hyl.gulimall.order.service.PaymentInfoService;
import com.hyl.gulimall.order.vo.*;
import com.hyl.gulimall.order.to.OrderCreateTo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyl.common.utils.PageUtils;
import com.hyl.common.utils.Query;

import com.hyl.gulimall.order.dao.OrderDao;
import com.hyl.gulimall.order.entity.OrderEntity;
import com.hyl.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    //远程服务
    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    //本地服务
    @Autowired
    OrderItemService orderItemService;

    @Autowired
    PaymentInfoService paymentInfoService;

    //工具
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 1. feign在远程调用之前要构造请求，这里存在feign远程调用丢失请求头的问题，因为他会创建一个新的request
     * 2. 这就导致了cookie丢失，登录状态丢失的问题
     * 3. feign在构造请求时可以调用请求拦截器，通过配置调用
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        /**异步编排每一个查询又会导致feign丢失请求头
         * 1. feign中若用RequestContextHolder获取当前请求上下文，是基于ThreadLocal做的
         * 2. 这里先在请求线程中拿出requestAttributes，再放入每个feign线程中
         */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // 保存请求上下文
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.查到用户所保存的地址信息
            List<MemberAddressVo> addresses = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(addresses);
        },executor);

        CompletableFuture<Void> getCartItemFuture = CompletableFuture.runAsync(() -> {
            // 保存请求上下文
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.远程查询购物车中的所有选项
            List<OrderItemVo> userCartItem = cartFeignService.getUserCartItem();
            confirmVo.setItems(userCartItem);
        },executor).thenRunAsync(()->{
            //3. 查询各商品是否有库存
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map((item) -> item.getSkuId()).collect(Collectors.toList());
            R skusHasStockR = wareFeignService.getSkusHasStock(skuIds);
            List<SkuStockVo> stockRes = skusHasStockR.getData(new TypeReference<List<SkuStockVo>>() {
            });
            //将库存信息转换成Map
            if(stockRes != null){
                Map<Long, Boolean> stockMap = stockRes.stream().collect(Collectors.toMap((SkuStockVo::getSkuId), SkuStockVo::getHasStock));
                confirmVo.setStocks(stockMap);
            }
            //远程查询Ware服务
        },executor);

        //4. 查询用户积分
        confirmVo.setIntegration(memberRespVo.getIntegration());

        //5. 给当前订单做防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        confirmVo.setToken(token);

        CompletableFuture.allOf(getAddressFuture,getCartItemFuture).get();
        return confirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        submitVoThreadLocal.set(orderSubmitVo);
        //拦截器拿到当前登录用户信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        /**
         * 验证令牌
         */
        String orderToken = orderSubmitVo.getOrderToken();
        String redisTokenPrefix = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId();
        //1.1通过lua脚本验证令牌,保证原子操作
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long scriptRes = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(redisTokenPrefix), orderToken);
        if(scriptRes == 0L){
            //2.验证失败
            responseVo.setCode(1);
            return responseVo;
        }else{
            //3.验证成功
            /**
             * 3.验证成功
             * 生成订单，验证价格，锁库存
             * 这里不用分布式事务存在问题：
             *     若远程锁库存时出现假失败（如库存锁住而返回的响应一直没到）
             *     这时就会出现订单服务回滚而库存服务不回滚情况（本地微服务的事务控制不了远程调用的服务）
             *     本地事务解决不了网络的问题
             */
            //3.1生成订单
            OrderCreateTo order = createOrder();
            //3.2验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //金额对比成功
                //3.3.保存订单
                saveOrder(order);
                //3.4.锁定库存，只要有异常回滚操作
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> itemsInSkuLock = order.getItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(itemsInSkuLock);
                //远程锁库存
                R orderLockR = wareFeignService.orderLockStock(wareSkuLockVo);
                if(orderLockR.getCode() == 0){
                    //锁成功
                    responseVo.setOrder(order.getOrder());
                    //TODO:远程扣减积分

                    //锁库存成功，订单创建完成，发消息给MQ(封装当前的OrderEntity)
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    responseVo.setCode(0);
                    return responseVo;
                }else{
                    //锁失败了
                    responseVo.setCode(3);
                    //throw new NoStockException(33L);
                    return responseVo;
                }
            }else{
                //金额对比有差距
                responseVo.setCode(2);
                return responseVo;
            }

        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 超市关闭订单
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的状态
        OrderEntity entityFromDB = this.getById(entity.getId());
        if(entityFromDB.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //当前订单仍为待支付
            OrderEntity updateEntity = new OrderEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateEntity);

            //给库存释放MQ队列发消息，主动要求解锁库存
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entityFromDB,orderTo);
            try {
                /**
                 * TODO:消息可靠性
                 * 消息丢失
                 * 1.做好消息确认机制（这里是publisher，consumer通过手动ack保证）
                 * 2.每一个发送的消息在数据库做好记录，定期将失败的进行重发
                 *
                 * 消息重复
                 * 方法的幂等性、防重表解决
                 *
                 * 消息积压
                 *
                 */
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){

            }
        }
    }


    /**
     * 创建订单
     * @return
     */
    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //生成订单号,Mybatis封装的生成订单号方法，基于时间
        String orderSn = IdWorker.getTimeId();
        //执行创建订单方法
        OrderEntity orderEntity = buildOrder(orderSn);
        //得到所有订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        //验价
        computePrice(orderEntity, itemEntities);
        orderCreateTo.setItems(itemEntities);
        orderCreateTo.setOrder(orderEntity);
        return orderCreateTo;
    }

    /**
     * 构建订单实体类
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberRespVo.getId());
        //获取收货地址信息
        OrderSubmitVo submitVo = submitVoThreadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        entity.setFreightAmount(fareVo.getFare());
        //设置收货信息
        entity.setReceiverCity(fareVo.getAddress().getCity());
        entity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        entity.setReceiverName(fareVo.getAddress().getName());
        entity.setBillReceiverPhone(fareVo.getAddress().getPhone());
        entity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        entity.setReceiverProvince(fareVo.getAddress().getProvince());
        entity.setReceiverRegion(fareVo.getAddress().getRegion());
        //设置订单状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        entity.setDeleteStatus(0);//删除状态,0未删除
        return entity;
    }

    /**
     * 构建所有订单项
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //获取所有订单项,最后确定每个购物项的价格(这里比较重要)
        List<OrderItemVo> currentUserCartItems = cartFeignService.getUserCartItem();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                //构建订单项数据
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息:订单号
        //2.商品spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(spuInfoVo.getId());
        itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        itemEntity.setSpuName(spuInfoVo.getSpuName());
        itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        //3.商品sku信息
        itemEntity.setSkuId(skuId);
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4.TODO:优惠信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //5.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().intValue() * cartItem.getCount());
        itemEntity.setGiftIntegration(cartItem.getPrice().intValue() * cartItem.getCount());
        //6.订单项价格信息
        //实际金额
        BigDecimal orgin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orgin.subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }

    /**
     * 验价方法
     *
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //订单总额,计算各种优惠的总额,计算积分和成长值总额
        BigDecimal couponAmount = new BigDecimal("0.0");
        BigDecimal promotionAmount = new BigDecimal("0.0");
        BigDecimal integrationAmount = new BigDecimal("0.0");
        Integer integration = 0;
        Integer growth = 0;
        BigDecimal total = new BigDecimal("0.0");

        for (OrderItemEntity entity : itemEntities) {
            couponAmount = couponAmount.add(entity.getCouponAmount());
            promotionAmount = promotionAmount.add(entity.getPromotionAmount());
            integrationAmount = integrationAmount.add(entity.getIntegrationAmount());
            growth += entity.getGiftGrowth();
            integration += entity.getGiftIntegration();
            total = total.add(entity.getRealAmount());
        }
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        orderEntity.setGrowth(growth);
        orderEntity.setIntegration(integration);
    }

    /**
     * 保存订单
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getItems();
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 获取订单的支付信息，封装支付vo
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        payVo.setOut_trade_no(order.getOrderSn());
        //支付宝仅支持小数点后两位,截取位数并向上取值（支付宝页面的要求）
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        OrderItemEntity entity = list.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> orders = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(
                    new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orders);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的异步通知结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1.保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //2.修改订单状态
        if(vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功
            String outTradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";

    }

    /**
     * 创建秒杀订单
     * @param seckillOrder
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrder.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(seckillOrder.getNum());
        orderItemService.save(itemEntity);
    }
}
